<template>
  <el-form
    ref="dataForm"
    :rules="rules"
    :model="temp"
  >
    <el-row>
      <el-col :span="6">
        <el-form-item label="旧密码" prop="currentPassword">
          <el-input v-model="temp.currentPassword" type="password" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="6">
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="temp.newPassword" type="password" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item>
      <el-button v-loading="loading" type="primary" @click="submit">修改密码</el-button>
    </el-form-item>
  </el-form>
</template>

<script>

import { updatePassword } from '@/api/user'

export default {
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码长度必须大于6位'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      temp: {
        currentPassword: '',
        newPassword: ''
      },
      rules: {
        currentPassword: [{ required: true, message: '旧密码必须填写' }],
        newPassword: [{ required: true, trigger: 'blur', validator: validatePassword }]
      }
    }
  },
  methods: {
    submit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          const data = {
            currentPassword: this.temp.currentPassword,
            newPassword: this.temp.newPassword
          }
          updatePassword(data).then((res) => {
            if (res.status === 204) {
              this.$notify({
                title: '成功',
                message: '修改密码成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '失败',
                message: res.data.error.message,
                type: 'warning',
                duration: 2000
              })
            }
          }).catch(err => {
            console.log(err)
          }).finally(() => {
            this.loading = false
          })
        }
      })
    }
  }
}
</script>
